package beanstao.util.plugin;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 */
public class SimplePluginManager<T> implements PluginManager<T>
{

	private final List<IPlugin> list = new ArrayList<IPlugin>();

	public SimplePluginManager(String... classNames) throws PluginException
	{
		for (String className : classNames)
		{
			this.loadPlugin(className);
		}
	}

	public SimplePluginManager(Class<? extends T>... classNames) throws PluginException
	{
		for (Class<? extends T> pluginClass : classNames)
		{
			this.loadPlugin(pluginClass);
		}
	}

	@SuppressWarnings("unchecked")
	public T get() throws NoPluginCanWorkException
	{
		for (IPlugin plugin : this.list)
		{
			if (plugin.canWork())
			{
				return (T) plugin;
			}
		}
		throw new NoPluginCanWorkException();
	}

	@SuppressWarnings("unchecked")
	public List<T> gets()
	{
		List<T> aList = new ArrayList<T>(this.list.size());
		for (IPlugin plugin : this.list)
		{
			if (plugin.canWork())
			{
				aList.add((T) plugin);
			}
		}
		return aList;
	}

	protected void loadPlugin(Class<? extends T> pluginClass) throws PluginException
	{
		if (pluginClass != null)
		{
			try
			{
				this.list.add((IPlugin) pluginClass.newInstance());
			}
			catch (Exception e)
			{
				throw new PluginException(pluginClass.getName(), e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void loadPlugin(String pluginClassName) throws PluginException
	{
		try
		{
			if (pluginClassName != null)
			{
				this.loadPlugin((Class<? extends T>) Class.forName(pluginClassName));
			}
		}
		catch (ClassNotFoundException e)
		{
		}
	}
}
